package com.hdw.auth.core;

import com.hdw.auth.api.BaseAuthFuService;
import com.hdw.auth.api.BaseAuthUseService;
import com.hdw.auth.api.UserService;
import com.hdw.auth.bean.model.BaseAuthFu;
import com.hdw.auth.bean.model.BaseAuthUse;
import com.hdw.auth.bean.model.SysUsers;
import com.hdw.auth.utils.PasswordUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

//@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private BaseAuthUseService baseAuthUseService;
    @Autowired
    private BaseAuthFuService baseAuthFuService;

    /**
     * @MethodName doGetAuthorizationInfo
     * @Description 权限配置类
     * @Param [principalCollection]
     * @Return AuthorizationInfo
     * @Author WangShiLin
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        //查询用户名称
        BaseAuthUse user = baseAuthUseService.getByCd(username);
        //添加角色和权限
        List<BaseAuthFu> fuList = baseAuthFuService.findByIdUse(user.getIdUse());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for(BaseAuthFu fu:fuList) {
            simpleAuthorizationInfo.addStringPermission(fu.getRoute());
        }
        return simpleAuthorizationInfo;
    }

    /**
     * @MethodName doGetAuthenticationInfo
     * @Description 认证配置类
     * @Param [authenticationToken]
     * @Return AuthenticationInfo
     * @Author WangShiLin
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (StringUtils.isEmpty(authenticationToken.getPrincipal())) {
            return null;
        }
        //获取用户信息
        String usernmae = authenticationToken.getPrincipal().toString();
        BaseAuthUse user = baseAuthUseService.getByCd(usernmae);
        if (user == null) {
            //这里返回后会报出对应异常
            return null;
        } else {
            String password = PasswordUtil.encrypt(usernmae, user.getPwd(), user.getSalt());
            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(usernmae, password, getName());
            return simpleAuthenticationInfo;
        }
    }
}
